module.exports = app => {
    const mongoose = app.mongoose;
    const Schema = mongoose.Schema;
    const tokenSchema = new Schema({
        name:String,
        token:String,
        expires_in:Number,
        meta:{
            createAt:{
                type:Date, 
                default:Date.now()
            },
            updateAt:{
                type:Date,
                default:Date.now()
            }
        }
    })
    tokenSchema.pre('save',function(next){
        if(this.isNew){
            this.createAt = this.updateAt = Date.now();
        }else{
            this.updateAt = Date.now();
        }
        next();
    });
    tokenSchema.statics = {
        async getToken (name) {
            return await this.findOne({name}).exec();
        },
        async saveToken (data,name) {
            let token = await this.getToken(name);
            if(token){
                token.token = data.token;
                token.expires_in = data.expires_in;
                token.save();
            }else{
                token = new Token({
                    name,
                    token:data.token,
                    expires_in:data.expires_in
                });
                token.save();
            }
            return token;
        }
    }
    const Token = mongoose.model('Token',tokenSchema);
    return Token;
}